package com.jijs.framework.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jijs.framework.CodeConstant;
import com.jijs.framework.dao.BaseDaoI;
import com.jijs.framework.model.Tree;
import com.jijs.framework.model.pmodel.AdeOrganization;
import com.jijs.framework.model.tmodel.TadeOrganization;
import com.jijs.framework.model.tmodel.TadeUser;

/**
 * 组织机构管理
 * 
 * @author jijs
 *
 */
@Service
public class OrganizationManagerService {

    @Autowired
    private BaseDaoI<TadeOrganization> organizationDao;

    @Autowired
    private BaseDaoI<TadeUser> userDao;

    public List<AdeOrganization> organizationTreeGrid(AdeOrganization organization) {

        String hql = " from TadeOrganization t ";
        List<AdeOrganization> list = new ArrayList<AdeOrganization>();
        List<TadeOrganization> listt = organizationDao.find(hql);
        if (listt != null && listt.size() > 0) {
            for (TadeOrganization torg : listt) {
                AdeOrganization dm = new AdeOrganization();
                BeanUtils.copyProperties(torg, dm);

                TadeOrganization tParent = torg.getTadeOrganization();

                if (tParent != null) {
                    dm.setOrgPid(tParent.getId());
                } else {
                    dm.setOrgPid(null);
                }

                list.add(dm);
            }
        }
        return list;
    }

    /**
     * 增加组织机构
     * 
     * @param org
     *            组织机构
     * @return 组织机构添加错误消息，如果null表示没有错误
     */
    public String add(AdeOrganization org) {

        // 进行重复性校验
        if (countDuplicates(org) >= 1) {
            return "已经存在一个机构名称相同的组织机构！";
        }

        TadeOrganization parent = null;
        if (!StringUtils.isEmpty(org.getOrgPid())) {
            parent = organizationDao.get(TadeOrganization.class, org.getOrgPid());

            if (parent == null) {
                return "找不到您选择的上级部门，请刷新页面重新提交。";
            }
        }

        // 保存TAdmOrganization
        TadeOrganization t = new TadeOrganization();
        t.setTadeOrganization(parent);

        BeanUtils.copyProperties(org, t);
        organizationDao.save(t);
        return null;
    }

    public List<Tree> organizationComboTree() {
        List<Tree> tadeOrganizationList = new ArrayList<Tree>();

        String sql = " from TadeOrganization t  ";

        List<TadeOrganization> list = organizationDao.find(sql);
        if (list == null || list.size() <= 0) {
            return tadeOrganizationList;
        }

        Set<String> hs = new HashSet<String>();
        for (TadeOrganization r : list) {

            TadeOrganization parent = r.getTadeOrganization();

            if (parent != null) {
                hs.add(parent.getId());
            }
        }
        for (TadeOrganization r : list) {
            Tree tree = new Tree();
            BeanUtils.copyProperties(r, tree);

            TadeOrganization parent = r.getTadeOrganization();

            if (parent != null) {
                tree.setPid(parent.getId());
                if (hs.contains(r.getId())) {
                    tree.setState("closed");
                }
            }

            tree.setText(r.getOrgName());
            tadeOrganizationList.add(tree);
        }

        return tadeOrganizationList;
    }

    /**
     * 获取组织机构详细信息
     * 
     * @param id
     *            组织机构ID
     * @return
     */
    public AdeOrganization getOrganization(String id) {

        AdeOrganization org = new AdeOrganization();

        TadeOrganization torg = organizationDao.get(TadeOrganization.class, id);
        BeanUtils.copyProperties(torg, org);

        TadeOrganization tparent = torg.getTadeOrganization();
        if (tparent != null) {
            org.setOrgPid(tparent.getId());
        }

        return org;
    }

    /**
     * 删除组织机构
     * 
     * @param id
     * @return
     */
    public String deleteOrganization(String id) {

        TadeOrganization ty = organizationDao.get(TadeOrganization.class, id);

        if (ty == null) {
            return "找不到指定的组织机构，请刷新页面后重新查询。";
        }

        Set<TadeOrganization> torganizations = ty.getTadeOrganizations();
        if (torganizations.size() > 0) {
            return "该组织机构下存在子机构，请先删除子机构后再删除该机构。";
        }

        Set<TadeUser> tusers = ty.getTadeUsers();
        for (TadeUser tuser : tusers) {
            if (CodeConstant.STATE_NORMAL.equals(tuser.getUserState())) {
                return "该组织机构下存在用户，请删除用户与当前机构的关系后，再删除该机构。";
            }
        }

        for (TadeUser tuser : tusers) {
            if (CodeConstant.STATE_FREEZE.equals(tuser.getUserState())) {
                tuser.setTadeOrganization(null);
                userDao.update(tuser);
            }
        }

        organizationDao.delete(ty);

        return null;
    }

    /**
     * 组织机构修改
     * 
     * @param org
     *            组织机构信息
     * @return 错误消息，如果没有错误修改成功，返回null
     */
    public String edit(AdeOrganization org) {

        // 画面上输入了父ID
        TadeOrganization parent = null;
        if (!StringUtils.isEmpty(org.getOrgPid())) {
            parent = organizationDao.get(TadeOrganization.class, org.getOrgPid());

            if (parent == null) {
                return "找不到您选择的上级部门，请刷新页面重新提交。";
            }
        }

        if (countDuplicates(org) >= 1) {
            return "已经存在一个机构名称相同的组织机构！";
        }

        TadeOrganization t = new TadeOrganization();
        BeanUtils.copyProperties(org, t);
        t.setTadeOrganization(parent);

        organizationDao.update(t);

        return null;
    }

    /**
     * 查找重复数据
     * 
     * @param org
     *            要查重的组织机构
     * @return 与指定的组织机构相同上级并且同名的数据条数
     */
    private int countDuplicates(AdeOrganization org) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgName", org.getOrgName());

        String pid = org.getOrgPid();
        // 如果PID为空，则查询父节点为空的组织机构
        if (StringUtils.isEmpty(pid)) {

            String countSql = "select count(*) from TadeOrganization t where t.id != :id and t.orgName = :orgName and t.tadeOrganization is null";
            params.put("id", org.getId());
            return organizationDao.count(countSql, params).intValue();

        } else {

            String countSql = "select count(*) from TadeOrganization t where t.id != :id and t.orgName = :orgName and t.tadeOrganization = :torganization";

            TadeOrganization parent = new TadeOrganization();
            parent.setId(org.getOrgPid());

            params.put("id", org.getId());
            params.put("torganization", parent);

            return organizationDao.count(countSql, params).intValue();
        }
    }
}
